import ast

from django.core.paginator import Paginator, EmptyPage
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from apps.tally.models import Tally
from apps.tally.serializers.user import TallySerializer
from apps.user.models import User
from utils.bases64 import main


class ApiAccount(APIView):
    """创建被记账"""

    def get(self, request):
        uid = request.GET.get("uid")  # 获取用户的id
        # 查询用户是否存在并且进行判断
        user = User.objects.filter(id=uid)
        if not user:
            ret = {
                "uid": 0,
                "data": "用户不存在，请重新登录！"
            }
            return JsonResponse(ret)
        return Response({"uid": user[0].id})

    def post(self, request):
        data = request.POST.get("data")
        types = request.POST.get("type")
        data1 = main(data)  # 将接受到的base64格式代码转化成python
        datas = ast.literal_eval(data1)  # 将接受到的数据转化成json格式
        print(datas["acmoney"])

        token = request.META.get("HTTP_TOKEN")
        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
        user_dict = jwt_decode_handler(token)
        user_id = user_dict['user_id']
        tal = {
            "aclass": datas["acclassid"],
            'user': user_id,
            'money': datas["acmoney"],
            "create_time": datas["actime"],
            "text": datas["acremark"],
            "kind": datas["zhifu"]
        }
        print(tal)
        serializer = TallySerializer(data=tal)
        serializer.is_valid(raise_exception=True)
        # 反序列化-数据保存
        serializer.save()
        print(serializer.data)
        ret = {"uid": user_id, "data": {"ret": "true", "msg": "修改成功!"}}
        return Response(ret)


class ApiFind(APIView):
    def get(self, request):
        datas = request.GET.get("data")
        types = request.GET.get("type")
        data1 = main(datas)  # 将接受到的base64格式代码转化成python
        datass = ast.literal_eval(data1)  # 将接受到的数据转化成json格式
        if types == "find":
            token = request.META.get("HTTP_TOKEN")
            jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
            user_dict = jwt_decode_handler(token)
            user_id = user_dict['user_id']
            user_ids = datass["jiid"]
            if datass["acclassid"]:
                print("521")
            if user_id == user_ids:
                class_id = datass["acclassid"]
                tally = Tally.objects.filter(aclass=class_id, user=user_id).order_by('-create_time')
                data = []
                page = datass["page"]
                print(type(page))
                SumInMoney = 0
                SumOutMoney = 0
                for i in tally:
                    if i.kind == "1":
                        SumInMoney += i.money
                    elif i.kind == "2":
                        SumOutMoney += i.money
                    else:
                        pass
                if page > 0:
                    # print(page)
                    paginator = Paginator(tally, 7)
                    print(paginator)
                    data = []
                    try:
                        page_skus = paginator.page(page)
                    except EmptyPage:
                        # 如果page_num不正确，默认给用户404
                        return Response({"uid": 0,
                                         "data": "用户不存在，请重新登录！"})
                    total_page = paginator.num_pages
                    # print(page_skus)
                    for i in page_skus:
                        data.append({
                            "acid": i.id,
                            "acmoney": i.money,
                            "acclassid": i.aclass.id,
                            "actime": i.create_time,
                            "acremark": i.text,
                            "jiid": i.user.id,
                            "zhifu": i.kind,
                        })

                    ret = {
                        "uid": user_id,
                        "data": {
                            "ret": "true",
                            "msg": {
                                "pagemax": total_page,
                                "page": page,
                                "SumInMoney": SumInMoney,
                                "SumOutMoney": SumOutMoney,
                                "count": len(tally),
                                "data": data
                            }
                        }
                    }
                    return Response(ret)
                elif page == 0:
                    tallyss = Tally.objects.filter(aclass=class_id, user=user_id,
                                                   create_time=datass["starttime"]).order_by('create_time')
                    paginator = Paginator(tallyss, 7)
                    print(paginator)
                    data = []
                    try:
                        page_skus = paginator.page(page + 1)
                    except EmptyPage:
                        # 如果page_num不正确，默认给用户404
                        return Response({"uid": 0,
                                         "data": "用户不存在，请重新登录！"})
                    total_page = paginator.num_pages
                    # print(page_skus)

                    for i in page_skus:
                        data.append({
                            "acid": i.id,
                            "acmoney": i.money,
                            "acclassid": i.aclass.id,
                            "actime": i.create_time,
                            "acremark": i.text,
                            "jiid": i.user.id,
                            "zhifu": i.kind,
                        })
                    ret = {
                        "uid": user_id,
                        "data": {
                            "ret": "true",
                            "msg": {
                                "pagemax": total_page,
                                "page": page,
                                "SumInMoney": SumInMoney,
                                "SumOutMoney": SumOutMoney,
                                "count": len(tallyss),
                                "data": data
                            }
                        }
                    }
                    return Response(ret)


class ApiModification(APIView):
    def get(self, request):
        datas = request.GET.get("data")
        types = request.GET.get("type")
        data1 = main(datas)  # 将接受到的base64格式代码转化成python
        datass = ast.literal_eval(data1)  # 将接受到的数据转化成json格式
        token = request.META.get("HTTP_TOKEN")
        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
        user_dict = jwt_decode_handler(token)
        user_id = user_dict['user_id']
        id = datass["acid"]

        if types == "get_id":
            u_id = datass["jiid"]
            if u_id == user_id:
                try:
                    tally = Tally.objects.get(id=id, user=u_id)
                except Tally.DoesNotExist:
                    ret = {'uid': 0, 'msg': '获取失败'}
                    return Response(ret)
                ret = {
                    "uid": u_id,
                    "data": {
                        "acid": tally.id,
                        "acmoney": tally.money,
                        "acclassid": tally.aclass.id,
                        "actime": tally.create_time,
                        "acremark": tally.text,
                        "jiid": u_id,
                        "zhifu": tally.kind,
                    }
                }
                return Response(ret)
            else:
                ret = {'uid': 0, 'msg': '获取失败'}
                return Response(ret)
        elif types == "get_image":
            ret = {
                "uid": user_id,
                "data": {
                    "ret": "false",
                    "msg": "此记账无对应的图片附件。"
                }
            }
            return Response(ret)

    def post(self, request):
        datas = request.POST.get("data")
        types = request.POST.get("type")
        data1 = main(datas)  # 将接受到的base64格式代码转化成python
        datass = ast.literal_eval(data1)  # 将接受到的数据转化成json格式
        token = request.META.get("HTTP_TOKEN")
        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
        user_dict = jwt_decode_handler(token)
        user_id = user_dict['user_id']
        id = datass["acid"]
        if types == "edit":

            data = {
                'id': id,
                "aclass": datass["acclassid"],
                'user': user_id,
                'money': datass["acmoney"],
                "create_time": datass["actime"],
                "text": datass["acremark"],
                "kind": datass["zhifu"]
            }
            try:  # 判断是否存在
                tally = Tally.objects.get(id=id)
            except Tally.DoesNotExist:
                ret = {"uid": 0, "data": {"ret": "false", "msg": "修改失败!"}}
                return JsonResponse(ret)
            serializer = TallySerializer(tally, data=data)
            serializer.is_valid(raise_exception=True)
            # 反序列化-数据保存(save内部会调用序列化器类的update方法)
            serializer.save()

            ret = {"uid": user_id, "data": {"ret": "true", "msg": "数据更新成功!"}}
            return Response(ret)
        elif types == "del":
            try:  # 判断是否存在
                tally = Tally.objects.filter(id=id)
            except Tally.DoesNotExist:
                ret = {"uid": 0, "data": {"ret": "false", "msg": "删除失败!"}}
                return JsonResponse(ret)
            uid = tally[0].user.id
            tally.delete()
            ret = {"uid": user_id, "data": {"ret": "true", "msg": "已经删除1条数据!"}}
            return Response(ret)

